package com.seanLab.tool;
import com.google.gson.Gson;
import com.seanLab.domain.Category;
import com.seanLab.domain.OriginCategory;
import org.junit.Test;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ttx on 13/09/2017.
 */

public class CategoryReader {

    @Test
    public static Map<Integer, Category> readCategory(String filePath){
        //convert json file to java obj
        String s = "";
        try {
            s = new String(Files.readAllBytes(Paths.get(filePath)));
        }catch (Exception e){
            System.out.println("File not found");
        }
        Gson gson = new Gson();
//        String s = "[{\"id\":\"257\",\"parent_id\":\"0\",\"name\":\"\\u65b0\\u6d6a\\u7f51\",\"coverpic\":\"\",\"ext\":\"a:1:{s:14:\\\"extension_conf\\\";a:0:{}}\",\"user_id\":\"11\",\"create_at\":\"2013-11-04 16:12:58\",\"modified_at\":\"2017-05-08 14:26:03\",\"url\":\"web\",\"url_alias\":\"\",\"keywords\":\"\",\"type\":\"1\",\"editor_group_key\":\"\",\"backend_name\":\"\"},{\"id\":\"258\",\"parent_id\":\"0\",\"name\":\"\\u624b\\u673a\\u65b0\\u6d6a\\u7f51\",\"coverpic\":\"\",\"ext\":\"a:1:{s:14:\\\"extension_conf\\\";a:0:{}}\",\"user_id\":\"11\",\"create_at\":\"2013-11-04 16:13:33\",\"modified_at\":\"2017-05-08 14:26:17\",\"url\":\"wap\",\"url_alias\":\"\",\"keywords\":\"\",\"type\":\"1\",\"editor_group_key\":\"\",\"backend_name\":\"\"}]";
        OriginCategory[] originData = gson.fromJson(s, OriginCategory[].class);
        Category[] data = new Category[originData.length];
        for(int i = 0;i < data.length;i++){
            data[i] = new Category();
            data[i].setCat_id(originData[i].getId());
            data[i].setName(originData[i].getName());
            data[i].setParent_id(originData[i].getParent_id());
        }

        //Set parentName, if parentID = 0, set ""
        Map<Integer, Category> map = new HashMap<Integer, Category>();
        for(Category category:data){
            map.put(category.getCat_id(),category);
        }
        return map;
    }

    public static void main(String[] args) {
        CategoryReader.readCategory("category.json");
    }
}